#pragma once
#include "Reactor.hpp"
#include "Listener.hpp"
#include <iostream>
#include <sys/eventfd.h>
#include <queue>
#include "Thread.hpp"
#include "BasePoll.hpp"

using namespace ThreadModule;
using task_t = std::function<void(std::string name)>;

static int count = 5; // 用来记录当前是第几个Reactor，注册对应的Eventfd
// eventfds属于Reactor_pool       //->
class Reactor_pool : public BasePool // 最底层模块Reactor_pool                   //->threads   ->各种Connection模块  ->eventfd模块
{                                    // queue属于Reactor_pool          //
public:
    /*创建子线程，给所有的子线程绑定一个func_t方法，让子线程去执行*/
    Reactor_pool(uint16_t local_port, int NUM) : _local_port(local_port), _NUM(NUM)
    {
        _reactor.SetOwner(this);
        auto coon = std::make_shared<Listener>(_local_port);
        _reactor.InsertConnection(coon); // Listener模块绑定到Reactor中
        for (int i = 0; i < (_NUM - 1); i++)
        {
            int skeventfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
            std::cout << "skeventfd" << skeventfd << std::endl;
            
            auto coon = std::make_shared<Eventfd>(skeventfd);
            std::cout << coon << std::endl;
            _eventfds_map.insert(std::make_pair(skeventfd, coon));

            task_t f = std::bind(&Reactor_pool::Thread_Handler, this, std::placeholders::_1);
            Thread thread(f);
            // thread.Start();
            threads.push_back(thread);
        }
        for (auto ch : threads)
        {
            ch.Start();
        }
        _reactor.Loop(); // 当有连接到来时，调用Listener模块的recver
    }

    void Thread_Handler(std::string name)
    {
        Lockguard lockguard(_lock);
        std::cout << "创建子线程成功" << std::endl;
        /*最后一步，每个子线程循环处理*/
        Reactor reactor; // 每个线程内部都有一个自己的Reactor,将eventfd封装成Connection
        reactor.SetOwner(this);
        //std::cout << "_eventfds_map[count]" << _eventfds_map[count] << std::endl;
        reactor.InsertConnection(_eventfds_map[count]); // 开始关心线程对应的Eventfd
        count++;
        reactor.Loop(); // 子线程进行Loop()
    }

    int GetNum()
    {
        return _NUM;
    }

    std::queue<int> &GetQueue()
    {
        return _sockfd_queue;
    }

    std::unordered_map<int, Connection_t> &GetEventfdMap()
    {
        return _eventfds_map;
    }

    ~Reactor_pool()
    {
        for (auto ch : threads)
        {
            ch.Join();
        }
    }

private:
    uint16_t _local_port;
    Reactor _reactor;
    std::unordered_map<int, Connection_t> _eventfds_map; // 记录所有子线程的eventfd  56789 往后依次对应9个Reactor，第一个Reactor是主线程
    std::queue<int> _sockfd_queue;                       // 存放所有的文件描述符的队列
    int _NUM;
    std::vector<Thread> threads;
    // Connection_t _listener_connection;//Listener模块绑定到Reactor中
    Mutex _lock;
};

// 总共NUM 10，创建9个子线程